package com.legal.service.chat.impl;

import com.legal.domain.dto.ChatHistory;
import com.legal.domain.po.ChatMemoryMsg;
import com.legal.service.chat.ChatService;
import com.legal.utils.BeanUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

import java.util.List;

@Service
@RequiredArgsConstructor
public class ChatServiceImpl implements ChatService {

    private final ChatClient chatClient;
    private final RedisChatHistory chatHistory;

    @Override
    public Flux<String> chat(String prompt) {
        return chatClient.prompt()
                .user(prompt)
                .stream() //表示流式调用，会一直返回数据，直到数据结束
                .content();
    }

    /**
     * 阻塞式调用
     * @param chatMemoryMsg
     * @return
     */
    @Override
    public String chat(ChatMemoryMsg chatMemoryMsg) {
        //1. 获取历史会话
        //chatHistory.save(chatMemoryMsg.getUserId(), chatMemoryMsg.getType(), chatMemoryMsg.getChatId());
        //2. 请求模型
        return chatClient.prompt()
                .user(chatMemoryMsg.getPrompt())
                .advisors(advisorSpec -> advisorSpec.param(AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY, chatMemoryMsg.getChatId()))
                .call() // 阻塞式调用
                .content();
    }

    /**
     * 聊天流式调用
     * @param chatMemoryMsg
     * @return
     */
    @Override
    public Flux<String> chatStream(ChatMemoryMsg chatMemoryMsg) {
        saveHistory(chatMemoryMsg);

        //4. 请求模型
        return chatClient.prompt() //创建一个prompt模版，里面可以添加参数，比如用户输入的prompt，或者会话id
                .user(chatMemoryMsg.getPrompt()) //user输入的问题
                .advisors(advisorSpec ->
                        advisorSpec.param(AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY,
                                chatMemoryMsg.getChatId()))
                .stream() //表示流式调用，会一直返回数据，直到数据结束
                .content(); //返回数据
    }

    private void saveHistory(ChatMemoryMsg chatMemoryMsg) {
        //1.获取历史会话
        List<String> chatIds = chatHistory.getChatIds(chatMemoryMsg.getType(), chatMemoryMsg.getUserNo());
        //2.判断是chatIds中否有会话chatId
        if(!chatIds.contains(chatMemoryMsg.getChatId())) {
            //2.1 说明redis中没有会话记录，则为第一次，创建一个会话，创建默认的title, 比如用户输入的prompt的前10个字
            String title = chatMemoryMsg.getPrompt().length() > 10
                    ? chatMemoryMsg.getPrompt().substring(0, 10) + "..."
                    : chatMemoryMsg.getPrompt();
            //2.2 拷贝一个历史会话
            ChatHistory history = BeanUtil.copy(chatMemoryMsg, ChatHistory.class);
            history.setTitle(title);
            //2.3 保存历史记录会话
            chatHistory.save(history);
        }else{
            //3.如果有会话chatId，则只更新会话id时间，让其排序在前，更新的是Zset
            ChatHistory history = BeanUtil.copy(chatMemoryMsg, ChatHistory.class);
            //3.2 更新会话时间
            chatHistory.updateChatTime(history);
        }
    }
}
